package com.aaa.sbm.configuration;

import com.aaa.sbm.util.MyCustomCache;
import com.aaa.sbm.util.RedisProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisClusterConfiguration;
import org.springframework.data.redis.connection.RedisNode;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import redis.clients.jedis.JedisPoolConfig;

//@Configuration  //启动加载  相当于过去的spring的xml配置文件中的<beans></beans>
public class RedisConfig {
    @Autowired
    private RedisProperties redisProperties;

    @Bean  //<bean id=jedisConnectionFactory  class=org.springframework.data.redis.connection.jedis.JedisConnectionFactory
    public JedisConnectionFactory jedisConnectionFactory(){
        //实例化
        JedisConnectionFactory jedisConnectionFactory =
                new JedisConnectionFactory(clusterConfig(),poolConfig());
        return  jedisConnectionFactory;
    }

    /**
     * 实例化redis集群配置
     * @return
     */
    @Bean  //<bean id=clusterConfig class=org.springframework.data.redis.connection.RedisClusterConfiguration
    public RedisClusterConfiguration clusterConfig(){
        //实例化
        RedisClusterConfiguration redisClusterConfiguration =
                new RedisClusterConfiguration();
        //获取配置文件中的节点
        String nodes = redisProperties.getNodes();
        //分割字符串
        String[] nodesArray = nodes.split(",");
        for (String node : nodesArray) {
            String[] nodeArray = node.split(":");
            //实例化redis节点
            RedisNode redisNode=new RedisNode(nodeArray[0],Integer.valueOf(nodeArray[1]));
            //向集群配置中添加集群节点
            redisClusterConfiguration.addClusterNode(redisNode);
        }

        return redisClusterConfiguration;
    }

    /**
     * 连接池配置
     * @return
     */
    @Bean  //<bean id=poolConfig class=redis.clients.jedis.JedisPoolConfig
    public JedisPoolConfig poolConfig(){
        //实例化连接池配置类
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        jedisPoolConfig.setMaxWaitMillis(redisProperties.getMaxWaitMillis());
        jedisPoolConfig.setTestOnBorrow(redisProperties.isTestOnBorrow());
        jedisPoolConfig.setMaxTotal(redisProperties.getMaxTotal());
        jedisPoolConfig.setMaxIdle(redisProperties.getMaxIdle());
        return jedisPoolConfig;
    }

    /**
     * 初始化MyCustomCache里面的jedisConnectionFactory对象
     */
    @Bean
    public void initJedisConnectionFactory(){
        MyCustomCache.setJedisConnectionFactory(jedisConnectionFactory());
    }
}
